package com.huanong.it.xwadmin.authority.common.handler;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huanong.it.xwadmin.authority.common.entity.Result;
import com.huanong.it.xwadmin.authority.common.utils.JwtUtil;
import com.huanong.it.xwadmin.authority.common.utils.SecurityUtils;
import com.huanong.it.xwadmin.authority.domain.User;
import com.huanong.it.xwadmin.authority.domain.model.LoginUser;
import com.huanong.it.xwadmin.authority.mapper.UserMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@Component
@AllArgsConstructor
@Data
@NoArgsConstructor
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtUtil jwtUtil;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Autowired
    private UserMapper userMapper;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json;charset=utf-8");
        response.setHeader(tokenHeader,jwtUtil.genJwt(authentication.getName()));
       Result r=  Result.succ("登录成功!欢迎您!"+ SecurityUtils.getCurrentUser().getUser().getNickname());
        response.getWriter().write(JSONUtil.toJsonStr(r));
        String name=((LoginUser) authentication.getPrincipal()).getUsername();
        User u= userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUsername,name));
        u.setLastLogin(new Date());
        userMapper.updateById(u);
    }
}
